package studio.raptor.dispatcher.server.config;

import com.zaxxer.hikari.HikariDataSource;
import javax.sql.DataSource;
import org.springframework.boot.autoconfigure.jdbc.DataSourceBuilder;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import studio.raptor.dispatcher.server.properties.MQProperties;
import studio.raptor.dispatcher.server.properties.ThreadPoolProperties;

/**
 * @author jack
 * @since 1.0
 */
@Configuration
public class DispatcherConfig {

  @Bean(name = "dispatcherDataSource")
  @ConfigurationProperties(prefix = "dispatcher.datasource")
  public DataSource dispatcherDataSource() {
    return DataSourceBuilder.create().type(HikariDataSource.class).build();
  }

  @Bean
  @ConfigurationProperties(prefix = "mq")
  public MQProperties mqProperties() {
    return new MQProperties();
  }

  @Bean
  @ConfigurationProperties(prefix = "thread.pool")
  public ThreadPoolProperties threadPoolProperties() {
    return new ThreadPoolProperties();
  }

  @Bean(destroyMethod = "destroy")
  public ThreadPoolTaskExecutor taskExecutor() {
    ThreadPoolTaskExecutor taskExecutor = new ThreadPoolTaskExecutor();
    taskExecutor.setCorePoolSize(threadPoolProperties().getCoreSize());
    taskExecutor.setQueueCapacity(threadPoolProperties().getCapacity());
    taskExecutor.setMaxPoolSize(threadPoolProperties().getMaxSize());
    taskExecutor.setWaitForTasksToCompleteOnShutdown(true);
    taskExecutor.afterPropertiesSet();
    return taskExecutor;
  }


}
